package com.app.library.base

import android.app.Activity
import android.app.Dialog
import android.graphics.Point
import android.os.Bundle
import android.view.Display
import android.view.Gravity
import android.view.Window
import android.view.WindowManager
import androidx.viewbinding.ViewBinding
import com.app.library.R
import com.app.library.utils.ViewBindingUtil

abstract class LibDialog<VB : ViewBinding>(private val activity: Activity) :
    Dialog(activity, R.style.CustomDialog) {

    private var mScreenPoint: Point = Point()

    var binding: VB? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ViewBindingUtil.inflateWithGeneric(this, layoutInflater)
        setContentView(binding!!.root)
        initDialogWindow(getScreenWidth())
        initView()
    }

    fun fillWidth(){
        val attr = window?.attributes
        attr?.width = WindowManager.LayoutParams.MATCH_PARENT
        window?.attributes = attr
    }
    abstract fun initView()

    private fun initDialogWindow(width: Float) {
        activity
        val dialogWindow: Window = window ?: return
        dialogWindow.setGravity(Gravity.CENTER)
        val m: WindowManager? = activity.windowManager
        val d: Display = m?.defaultDisplay ?: return // 获取屏幕宽、高用
        try {
            d.getSize(mScreenPoint)
        } catch (ignore: NoSuchMethodError) { // Older device
            mScreenPoint.x = d.width
            mScreenPoint.y = d.height
        }
        val p: WindowManager.LayoutParams = dialogWindow.attributes // 获取对话框当前的参数值
        p.width = (mScreenPoint.x * width).toInt()
        dialogWindow.setWindowAnimations(R.style.MpDialogCommonAnim)
        dialogWindow.attributes = p
    }

    override fun dismiss() {
        if (activity != null && !activity.isDestroyed && !activity.isFinishing && isShowing) {
            try {
                super.dismiss()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    open fun getScreenWidth(): Float {
        return 0.8f
    }
}